package com.mach.platform.sprider.dev.virdev;

import com.mach.platform.sprider.dev.UU;
import com.mach.platform.sprider.getter.CmdMainWork;
import com.mach.platform.sprider.getter.DevFactory;
import com.mach.platform.sprider.getter.GeneralDev;
import com.mach.platform.sprider.getter.GeneralModbusDev;
import com.mach.platform.sprider.getter.DataLogService;
import com.mach.platform.util.SqlHelper;
import lombok.extern.slf4j.Slf4j;

import java.sql.SQLException;
import java.util.Map;

@Slf4j
public class TempKeeperAutoCtrl extends GeneralModbusDev implements VirDev {

    private Map<Object,Object> devPropsMap;


    private SqlHelper sqlHelper;
    private  DataLogService dataLogService;
    private  Map<String, Object> devInfoMap;
    private boolean isOpen = false;
    private GeneralDev[] tas;
    private long lastCmdTime = 0;
//    private  Integer devId;


    public TempKeeperAutoCtrl(Map<String, Object> devInfoMap, SqlHelper sqlHelper, DataLogService dataLogService) throws SQLException {
        super(devInfoMap, sqlHelper, dataLogService);

        this.devInfoMap = devInfoMap;

        this.sqlHelper = sqlHelper;

        this.dataLogService = dataLogService;

        initCtrInfo();
    }

    private void initCtrInfo(){

        this.tas = new GeneralDev[4];

        this.tas[0] = DevFactory.getById(136); //1#冷却塔
        this.tas[1] = DevFactory.getById(137); //2#冷却塔
        this.tas[2] = DevFactory.getById(138); //3#冷却塔
        this.tas[3] = DevFactory.getById(139); //4#冷却塔
    }

    @Override
    protected void pick() {
        try {
            this.devPropsMap = sqlHelper.getMapFrTable("name", "value",
                    "select name, value value " +
                            " from iot_dev_prop prop " +
                            " where prop.dev_id=" + this.devId);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Integer auto = Integer.parseInt((String)this.devPropsMap.get("auto"));
        if(auto == 1){
            this.isOpen = true;
        }else{
            this.isOpen = false;
        }
        if(!this.isOpen ){
            UU.sleep(1000*5);
            return;
        }else{

        }
        long cur = System.currentTimeMillis();
        if( (cur - this.lastCmdTime) <  1000*60*5){
            UU.sleep(1000*5);
            return;
        }

        Double upValue = Double.parseDouble((String)this.devPropsMap.get("setUp"));
        Double downValue = Double.parseDouble((String)this.devPropsMap.get("setDown"));
        GeneralDev templDev = DevFactory.getById(79); //温度传感器
        try {
            Double templ = (Float) templDev.getValueByCollName("温度") * 1.0;

            if(templ < downValue){ //超下限
                GeneralDev ta = this.findTaByStatus(1);
                if(ta != null){
                    CmdMainWork.commitCmd(ta.getDevId(),"close",null);
                    this.lastCmdTime = System.currentTimeMillis();
                }
            }
            if(templ > upValue){ //超上限
                GeneralDev ta = this.findTaByStatus(0);
                if(ta != null){
                    CmdMainWork.commitCmd(ta.getDevId(),"open",null);
                    this.lastCmdTime = System.currentTimeMillis();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            UU.sleep(1000*1);
        }
    }

    private GeneralDev findTaByStatus(Integer status) {

        GeneralDev ta = null;
        for( GeneralDev dev : this.tas ){
            try {
                Object runStatusObj= dev.getValueByCollName("运行状态");
                Short curStatus = null;
                if(runStatusObj != null){
                    curStatus = (Short)runStatusObj;
                    if(status == curStatus.intValue()){
                        return dev;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return ta;
    }

    @Override
    public void cmd(Integer cmdLogId,String cmd, String param) {

        try {
            Integer devTypeId = (Integer)this.devInfoMap.get("devTypeId");

//            Map<Object, Object> addrMap = sqlHelper.getMapFrTable("name", "valueAddr",
//                    "select name, value_addr valueAddr " +
//                            " from iot_coll_items colls " +
//                            " where colls.dev_type_id=" + devTypeId);

//            if(ctrModelValue != null && ctrModelValue.equals(1.0)){//远程
            if("open".equals(cmd) ){
                this.isOpen = true;
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('auto','1',"+devId+")");
            }
            if("close".equals(cmd) ){
                this.isOpen = false;
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('auto','0',"+devId+")");
            }
            if("setUp".equals(cmd) && param != null ){
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('setUp','"+param+"',"+devId+")");
            }
            if("setDown".equals(cmd) && param != null ){
                sqlHelper.update("replace into iot_dev_prop(name,value,dev_id)" +
                        "value('setDown','"+param+"',"+devId+")");
            }

            sqlHelper.update(
                    "update iot_dev_cmd_log set resp_code=1,resp_ctx='"+EXE_SUCS_CTX+"' where id=" + cmdLogId);

        } catch (Exception e) {
            e.printStackTrace();
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_code=0,resp_ctx='"+e.getLocalizedMessage()+"' where id=" + cmdLogId);
        }finally {
            sqlHelper.updateAsync(
                    "update iot_dev_cmd_log set resp_time=now() where id=" + cmdLogId);
        }




        return;
    }

    @Override
    public Integer getDevId() {
        return this.devId;
    }


}
